package com.wzh.yebServe.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzh.yebServe.pojo.ResultBean;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author wzh
 * @create 2022/11/9 11:34
 * @Description: 当访问接口没有 权限时，自定义返回结果
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
          response.setContentType("application/json");
          response.setCharacterEncoding("UTF-8");
          PrintWriter writer = response.getWriter();
          ResultBean error = ResultBean.error("权限不足，请联系管理员");
          error.setCode(403);
          writer.write(new ObjectMapper().writeValueAsString(error));
          writer.flush();
          writer.close();
    }
}
